<?php

namespace app\admin\controller;

use think\Controller;
use think\facade\Validate;

class Login extends Controller
{
    // 登录
    public function login()
    {
        if (request()->isAjax()) {
            $data = [
                'username' => input('username'),
                'password' => input('password')
            ];
            $validate = Validate::make([
                'username|用户名' => 'require',
                'password|密码' => 'require'
            ]);
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            } else {
                $adminInfo = model('Admin')->where(['username' => $data['username'], 'password' => md5($data['password'])])->find();
                if ($adminInfo) {
                    if ($adminInfo['status'] == 1) {
                        cookie('adminId', $adminInfo['id']);
                        $this->success('登录成功');
                    } else {
                        $this->error('此账号被禁用！');
                    }
                } else {
                    $this->error('用户名或者密码错误！');
                }
            }
        }
        return view();
    }

    // 注销登录
    public function logout()
    {
        cookie('adminId', null);
        $this->success('注销登录成功');
    }

    // 清除缓存
    public function clearCache()
    {
        $path = env('runtime_path');
        if(is_dir($path)){
            $p = scandir($path);
            foreach($p as $val){
                if($val !="." && $val !=".."){
                    if(is_dir($path.$val)){
                        $this->delDir($path.$val.'/');
                        @rmdir($path.$val.'/');
                    }else{
                        unlink($path.$val);
                    }
                }
            }
        }
        $this->success('清除成功');
    }

    // 删除文件夹
    private function delDir($path){
        if(is_dir($path)){
            $p = scandir($path);
            foreach($p as $val){
                if($val !="." && $val !=".."){
                    if(is_dir($path.$val)){
                        $this->delDir($path.$val.'/');
                        @rmdir($path.$val.'/');
                    }else{
                        unlink($path.$val);
                    }
                }
            }

        }
    }
}
